package com.example.clxy.util;


import com.example.clxy.result.WebRestResult;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author lhq
 */
@Component
public class FileUtil {

	//返回前端地址前缀
	public static String FilePathUrl ;
	//文件存储路径
	public static String UploadFilePathUrl ;
	//得到是Windows下的 还是 linux下运行
	public static String system;

	public String getSystem() {
		return system;
	}

	@Value("${run.server.system}")
	public void setSystem(String system) {
		FileUtil.system = system;
	}

	public  String getFilePathUrl() {
		return FilePathUrl;
	}

	@Value("${upload.filePathUrl}")
	public  void setFilePathUrl(String filePathUrl) {
		FilePathUrl = filePathUrl;
	}

	public  String getUploadFilePathUrl() {
		return UploadFilePathUrl;
	}

	@Value("${upload.uploadFilePathUrl}")
	public  void setUploadFilePathUrl(String uploadFilePathUrl) {
		UploadFilePathUrl = uploadFilePathUrl;
	}

	/**
	 * 用于校验文件格式,校验文件大小
	 * @param file
	 * @return
	 */
	public static WebRestResult validateFile(MultipartFile file,String operationuser) {
		WebRestResult result = new WebRestResult();
		if (operationuser == null) {
			result.setResult(WebRestResult.FAILURE);
			result.setMessage("请传入上传用户的用户id");
			return result;
		}
		String fileType = ".pdf,.jpg1024,.jpeg,.png,.bmp";
		//5 * 1024 * 1024
		String fileSizeLimit = "5242880";
		if (!file.isEmpty()) {
			try {
				String oldFileName = file.getOriginalFilename();
				if (Tools.isEmpty(oldFileName)) {
					result.setResult(WebRestResult.FAILURE);
					result.setMessage("文件格式错误：无文件名！");
					return result;
				}
				if (!FileUtil.checksSuffix(oldFileName, fileType)) {
					result.setResult(WebRestResult.FAILURE);
					result.setMessage("文件格式错误：文件格式错误：非法后缀名！");
					return result;
				}
				byte[] bytes = new byte[0];
				bytes = file.getBytes();
				if (!FileUtil.checkFileSize(bytes, fileSizeLimit)) {
					result.setResult(WebRestResult.FAILURE);
					result.setMessage("文件太大");
					return result;
				}
			} catch (IOException e) {
				e.printStackTrace();
				result.setMessage("简历文件上传失败," + e.getMessage());
				result.setResult(WebRestResult.FAILURE);
			}
		} else {
			result.setMessage("文件不能为空！");
			result.setResult(WebRestResult.FAILURE);
		}
		result.setResult(WebRestResult.SUCCESS);
		result.setMessage("文件校验成功！");
		return result;
	}

	//获取新文件命名
	public static String getApplyInnovationFileName(String oldFileName) {
		String newFileName = "/userfiles/"  + "/photo/";
		return newFileName;
	}


	//获取新文件命名
	public static String getFileName(String oldFileName, String operationUser ) {
		String datestr = Tools.dateToStr(new Date());
		String suffix = oldFileName.substring(oldFileName.indexOf(".")).toLowerCase();
		String newFileName = "/userfiles/" + operationUser + "/photo/"+ datestr.substring(0, 4) + "/" + datestr.substring(4, 6)+ "/" + UUIDUtil.randomUUID() + suffix;
		return newFileName;
	}

	//保存文件
	public static String writeFile(MultipartFile file, String fileName , String fileUploadLocation)throws IOException{
		//生成上传路径
		String realPath = fileUploadLocation + "/" + fileName;

		File newFile = new File(realPath);

		//判断文件目录是否存在
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdirs();
		}

		if (!newFile.exists()) {
			newFile.createNewFile();
		}
		//保存文件
		file.transferTo(newFile);
		return realPath;
	}

	//删除文件
	public static void delFile(String fileUrl) {
		if(!Tools.isEmpty(fileUrl)){
			File file = new File(fileUrl);
			if (file.exists() && file.isFile()) {
				file.delete();
			}
		}
	}

	//检查文件后缀
	public static Boolean checksSuffix(String fileName,String fileType){
		if (fileName.indexOf(".") == -1) {
			return false;
		}
		String suffix = fileName.substring(fileName.indexOf(".")).toLowerCase();

		if (fileType.indexOf(suffix) == -1) {
			return false;
		}
		return true;
	}


	//检查文件大小
	public static Boolean checkFileSize(byte[] bytes ,String fileSizeLimit){
		int fileSize = Integer.parseInt(fileSizeLimit);
		if (bytes.length > fileSize) {
			return false;
		}
		else
			return true;
	}

	//检查文件是否存在
	public static boolean existFile(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	public static void main(String args[]){
		System.out.println(Tools.dateToStr(new Date()));
	}

	public static String getAbsolutePath(String filepath) {
		String replacePath = filepath;
		if (FileUtil.system.contains("linux")) {
			replacePath = filepath.replace('\\', '/');
		}
		return UploadFilePathUrl+replacePath;
	}

	//合并pdf
	/**
	 * 合并原pdf为新文件
	 *
	 * @param files   pdf绝对路径集
	 * @param newfile 新pdf绝对路径
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void mergePdfFiles(List<String> files, String newfile) throws IOException, DocumentException {
		Document document = new Document(new PdfReader(files.get(0)).getPageSize(1));
		PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
		document.open();
		for (int i = 0; i < files.size(); i++) {
			PdfReader reader = new PdfReader(files.get(i));
			int n = reader.getNumberOfPages();
			for (int j = 1; j <= n; j++) {
				document.newPage();
				PdfImportedPage page = copy.getImportedPage(reader, j);
				copy.addPage(page);
			}
			reader.close();
		}
		copy.close();
		document.close();
	}


}
